// import config from '@/common/config.js'
// const config = "ws://192.168.3.98:8088/websocket"
const config = "wss://lvp.yipaijh.cn/prod-api/websocket";

class WebsocketUtil {
	constructor(url, time) {
		this.socketTask = null;
		this.token = null;
		this.chatId = "";
		this.message_callbacks = [];
		this.is_open_socket = false;
		this.url = url;
		this.data = null;
		this.timeout = time;
		this.heartbeatInterval = null;
		this.reconnectTimeOut = null;
	}

	connectSocketInit(callback) {
		return new Promise((resolve, reject) => {
			if (this.is_open_socket) {
				callback && callback();
				resolve();
				return;
			}
			if (!this.token) {
				reject(new Error("Token is not set"));
				return;
			}
			try {
				this.socketTask = uni.connectSocket({
					url: this.url + '/' + this.token + (this.chatId ? `?chatId=${this.chatId}` :
						''),
					success: () => {
						console.log("【websocket】正准备建立websocket中...");
					},
					fail: (error) => {
						console.error("【websocket】连接失败", error);
						reject(error);
					}
				});

				this.socketTask.onOpen((res) => {
					console.log("【websocket】WebSocket连接正常！", res);
					clearTimeout(this.reconnectTimeOut);
					clearInterval(this.heartbeatInterval);
					this.is_open_socket = true;
					this.start();
					this.listenMessage();
					callback && callback();
					resolve();
				});

				this.socketTask.onError((error) => {
					console.log('【WebSocket】连接错误，请检查！', error);
					this.is_open_socket = false;
					reject(error);
				});

				this.socketTask.onClose(() => {
					console.log("WebSocket已经被关闭了");
					this.is_open_socket = false;
					this.reconnect();
				});
			} catch (error) {
				console.error("【websocket】初始化错误", error);
				reject(error);
			}
		});
	}

	send(value) {
		return new Promise((resolve, reject) => {
			if (!this.is_open_socket) {
				reject(new Error("WebSocket is not open"));
				return;
			}
			this.socketTask.send({
				data: value,
				success() {
					resolve();
				},
				fail(error) {
					reject(error);
				}
			});
		});
	}

	start() {
		this.heartbeatInterval = setInterval(() => {
			this.data = {
				type: 8
			};
			this.send(JSON.stringify(this.data)).catch(error => {
				console.error("Heartbeat send error", error);
			});
		}, this.timeout);
	}

	reconnect() {
		clearInterval(this.heartbeatInterval);
		if (!this.is_open_socket) {
			this.reconnectTimeOut = setTimeout(() => {
				this.connectSocketInit().catch(error => {
					console.error("Reconnection error", error);
				});
			}, 3000);
		}
	}

	listenMessage() {
		if (!this.is_open_socket) return false;
		this.socketTask.onMessage((res) => {
			if (!res.data) return;
			try {
				let data = JSON.parse(res.data);
				this.message_callbacks.forEach(callback => {
					if (typeof callback === 'function') {
						callback(data);
					}
				});
			} catch (error) {
				console.error("Message parsing error", error);
			}
		});
	}

	getMessage(fun) {
		if (typeof fun === 'function') {
			this.message_callbacks.push(fun);
		}
	}

	closeSocket() {
		return new Promise((resolve, reject) => {
			if (this.is_open_socket) {
				this.is_open_socket = false;
				this.message_callbacks = [];
				this.socketTask.close({
					success: () => {
						console.log("【websocket】WebSocket连接关闭成功！");
						resolve();
					},
					fail: (error) => {
						console.error("【websocket】WebSocket关闭失败", error);
						reject(error);
					}
				});
			} else {
				resolve();
			}
		});
	}
}

module.exports = new WebsocketUtil(config, 20000);